<?php
namespace app\api\controller;

use app\BaseController;
use app\Request;
use learn\services\UtilService as Util;
use think\exception\ValidateException;
use app\models\user\User;
use learn\services\CacheService;

use app\models\user\UserToken;

use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Sms\V20190711\SmsClient;
use TencentCloud\Sms\V20190711\Models\SendSmsRequest;


class AuthController extends BaseController
{


    /**
     * 退出登录
     * @param Request $request
     */
    public function logout(Request $request)
    {
        $request->tokenData()->delete();
        return app('json')->success('成功');
    }

    /**
     * 验证码
     */
    public function verify (Request $request)
    {
        list($phone) = Util::getMore([['phone',0]],$request, true);
        try {
            if(preg_match("/^1[345678]{1}\d{9}$/",$phone)){
            }else{
                return app('json')->fail("手机号格式错误");
            }
        } catch (ValidateException $e) {
            return app('json')->fail($e->getError());
        }

        $time = 60*10;
        
        
        if(CacheService::get('code_'.$phone))
        
            // return app('json')->success('发送成功');
            return app('json')->fail($time.'秒内有效');
            
        $code = rand(100000,999999);
        
        $sms = new Sms();


        $res = $sms->sendCodeSms($phone, $code);
        if ($res === false) return app('json')->fail('验证码发送失败');
        CacheService::set('code_'.$phone, $code, $time);
        return app('json')->success('发送成功');

        //腾讯
        $cred = new Credential("AKIDiDScYM48gyzjGXcLzmJbcLHxLSJxvhp9", "KQHG1ZrvkJceXGVqIXYM0PksvkkU4OaZ");//API密钥管理
        $httpProfile = new HttpProfile();
        $httpProfile->setEndpoint("sms.tencentcloudapi.com");//网址

        $clientProfile = new ClientProfile();//签名算法
        $clientProfile->setHttpProfile($httpProfile);//设置http相关参数
        $client = new SmsClient($cred, "", $clientProfile);
        $req = new SendSmsRequest();
        
        //请求参数
        $params = '{
        "PhoneNumberSet":["+86'.$phone.'"],
        "TemplateID":"647716",
        "Sign":"万名",
        "TemplateParamSet":["'.$code.'"],
        "SmsSdkAppid":"1400390364"}';
            
        $req->fromJsonString($params);

        $resp = $client->SendSms($req);
        $sad=json_decode(json_encode($resp), true);
        if ($sad["SendStatusSet"][0]['Code']=='Ok') {
            CacheService::set('code_'.$phone, $code, $time);
            return app('json')->success('发送成功');
        }else{
            return app('json')->success('发送失败');
        }
        

    }

    /**
     * 登录
     */
    public function molibe (Request $request)
    {
        list($phone, $captcha) = Util::postMore([['phone',''], ['captcha','']],$request, true);
        
        //验证手机号
        try {
            if (preg_match("/^1[345678]{1}\d{9}$/",$phone)) {
            }else{
                return app('json')->fail("手机号格式错误");
            }
        } catch (ValidateException $e) {
            return app('json')->fail($e->getError());
        }

        //验证验证码
        $verifyCode = CacheService::get('code_'.$phone);
        if(!$verifyCode)
            return app('json')->fail('请先获取验证码');
        $verifyCode = substr($verifyCode, 0, 6);
        if($verifyCode != $captcha)
            return app('json')->fail('验证码错误');

        $userinfo = User::where("phone",$phone)->find();

        if (!$userinfo) {
            // 用户不存在
            $user = new User;
            $user->phone = $phone;
            $user->password = md5("111111");
            $user->create_time = time();
            $user->save();
            // 获取自增UID
            $uid = $user['uid'];
        }else{
            $uid = $userinfo["uid"];
        }
        
        if (!$userinfo['status'])
            return app('json')->fail('已被禁止，请联系管理员');

        $times = strtotime("+ 500hour");
        $token = UserToken::tokenCreate($uid,$times);
        if ($token) {
            return app('json')->success('登录成功', ['token' => $token, 'expires_time' => $times]);
        } else
            return app('json')->fail('登录失败');
        
    }
 
    
}
